<template>
  <ul class="el-upload-list el-upload-list--picture-card">
    <li class="el-upload-list__item is-ready">
      <el-image ref="image" :src="value" fit="contain" style="width: 100%">
        <template #error>
          <el-icon :size="146" class="el-upload-list__item-thumbnail">
            <Picture />
          </el-icon>
        </template>
      </el-image>

      <el-image-viewer
        v-if="showViewer"
        :url-list="[value]"
        @close="showViewer = false"
      />

      <div class="el-upload-list__item-actions">
        <template v-if="value">
          <el-form>
            <el-button text type="primary" @click="showViewer = true">
              预览
            </el-button>
          </el-form>
          <br />

          <el-button text type="primary" @click="value = ''">删除</el-button>

          <br />
        </template>

        <el-upload
          ref="upload"
          :limit="1"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChangeHandler"
          :on-exceed="onExceedHandler"
          accept=".jpg,.png,.jpeg"
        >
          <template #trigger>
            <el-button text type="primary">选择图片</el-button>
          </template>
        </el-upload>
        <br />
        <slot name="button"> </slot>
      </div>
    </li>
  </ul>
</template>
<script>
import { compressImg } from '@/utils/compress'

export default {
  name: 'JImageChooser',
  emits: ['update:modelValue'],
  props: {
    modelValue: {
      type: String,
    },
    compress: {
      type: Boolean,
      default: true,
    },
    maxSize: {
      type: Number,
      default: 100,
    },
  },
  data() {
    return {
      showViewer: false,
    }
  },
  computed: {
    value: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      },
    },
  },
  methods: {
    onChangeHandler(file) {
      let reader = new FileReader() //创建文件读取对象
      reader.readAsDataURL(file.raw)
      //监听文件读取结束后事件
      reader.onloadend = (e) => {
        if (this.compress) {
          compressImg(e.target.result, this.maxSize).then((res) => {
            this.value = res
          })
        } else {
          this.value = e.target.result
        }
      }
    },
    onExceedHandler(files) {
      let upload = this.$refs.upload
      upload.clearFiles()
      upload.handleStart(files[0])
    },
  },
}
</script>
<style lang="scss" scoped>
.el-upload-list__item-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
</style>
